package com.mindao.app.site.controller;


import java.io.IOException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.controller.BaseWxDeveloperController;
import com.jfinal.weixin.sdk.msg.in.InImageMsg;
import com.jfinal.weixin.sdk.msg.in.InLinkMsg;
import com.jfinal.weixin.sdk.msg.in.InLocationMsg;
import com.jfinal.weixin.sdk.msg.in.InShortVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.InVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.jfinal.weixin.sdk.msg.in.event.InCustomEvent;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMassEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.in.event.InShakearoundUserShakeEvent;
import com.jfinal.weixin.sdk.msg.in.event.InTemplateMsgEvent;
import com.jfinal.weixin.sdk.msg.in.event.InVerifyFailEvent;
import com.jfinal.weixin.sdk.msg.in.event.InVerifySuccessEvent;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutNewsMsg;
import com.mindao.app.ea.service.ResourceService;
import com.mindao.app.site.exception.EnrollException;
import com.mindao.app.site.model.Event;
import com.mindao.app.site.service.EventService;
import com.mindao.utils.WeixinConfUtils;
import com.mindao.utils.config.EaCommonUtils;

/**
 * 微信开发者后台
 * 接收微信服务器消息--敏道公司
 * 
 * 
 * 如果是验证消息，直接返回参数echostr 
 * 如果是粉丝发送的消息或者粉丝的事件消息，自动解析成 InMsg 并分发到相应的处理方法
 */
@Controller
@RequestMapping("/site/sitewxdeveloper")
public   class SiteWxDeveloperController  extends BaseWxDeveloperController {
	private final Logger log = LoggerFactory.getLogger(SiteWxDeveloperController.class);
	
	@Autowired
	private ResourceService resourceService;
	
	@Autowired
	protected EventService eventService;
 
	@Override
	public   ApiConfig getApiConfig(){ 
		return WeixinConfUtils.getApiConfig();
	}
	
 
	//微信接口验证
	@Override
	protected boolean checkSignature(HttpServletRequest request){
		String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        ApiConfig apiConfig = WeixinConfUtils.getApiConfig();
        if (!StringUtils.isBlank(signature) && !StringUtils.isBlank(timestamp) && !StringUtils.isBlank(nonce)){
	        String[] tmpArr={ apiConfig.getToken(),timestamp,nonce};
	        Arrays.sort(tmpArr);
	        String tmpStr=super.ArrayToString(tmpArr);
	        tmpStr=super.SHA1Encode(tmpStr);
	        if(tmpStr.equalsIgnoreCase(signature)){
				return true;
			}else{
				return false;
			}
        }else{
        	return false;
        }
	}
	/**
	 * 处理文本事件，自动回复
	 */
	@Override
	protected boolean processInTextMsg(HttpServletResponse response,InTextMsg inTextMsg) {
		// TODO Auto-generated method stub
		log.info("00000000000000000000000000");
 
		ApiConfigKit.setDevMode(true);
        String echo = doProcessInTextMsg(response, inTextMsg);
		if (echo!=null){
			super.echoTxt(response, inTextMsg, echo);
		}
		return echo==null?false:true;
	}
	private String doProcessInTextMsg(HttpServletResponse response,
			InTextMsg inTextMsg) {
		String echo=null;
		log.info("111111111111111111111111111");
		String msgContent= inTextMsg.getContent().replaceAll("，", ",").replaceAll("：", ":");
		if (msgContent.indexOf("wxsdk")>=0){
			echo="<a href=\""+EaCommonUtils.getRequestServerPath(EaCommonUtils.getRequest()) +"/site/sitewx/wxsdk.do\">wxsdk</a>";
		}
		if (msgContent.indexOf("报名")>=0){
			Event event=eventService.getCurrentEvent();
			log.info("222222222222222222222222222222");
			if (event!=null){
				if (msgContent.startsWith("报名:") &&  msgContent.indexOf(",")>0){
					String userInfos=msgContent.substring("报名:".length());
					String userInfArr[]=userInfos.split(",");
					try {
						log.info("3333333333333333333333333333");
						eventService.createEventEnroll(event, null, null, inTextMsg.getFromUserName(), null, userInfArr[0], userInfArr[1]);
						echo="报名成功";
						log.info("444444444444444444444444444444444");
					} catch (EnrollException e) {
						// TODO Auto-generated catch block
						echo="报名失败，格式不正确。标准格式“报名:姓名,qq号”";
					}
				}else{
					echo="报名失败，格式不正确。标准格式“报名:姓名,qq号”";
				}
			}else{
				echo="报名已经截止";
			}

		}
		log.info("echo:"+echo);

		return echo;
	}
	@RequestMapping
	protected void enrollTest(HttpServletResponse response,String msgContent) {
		InTextMsg inTextMsg =new InTextMsg("toUserName",   "fromUserName",   1, "text");
		inTextMsg.setContent(msgContent);
        String echo = doProcessInTextMsg(response, inTextMsg);
		try {
			response.setHeader("Content-type", "text/html;charset=UTF-8");  
			response.getWriter().print(echo);
			response.getWriter().flush();
			response.getWriter().close();			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	protected boolean processInImageMsg(HttpServletResponse response,InImageMsg inImageMsg) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean processInVoiceMsg(HttpServletResponse response,InVoiceMsg inVoiceMsg) {
		// TODO Auto-generated method stub
		return false;
 
	}

	@Override
	protected boolean processInVideoMsg(HttpServletResponse response,InVideoMsg inVideoMsg) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean processInShortVideoMsg(HttpServletResponse response,InShortVideoMsg inShortVideoMsg) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean processInLocationMsg(HttpServletResponse response,InLocationMsg inLocationMsg) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean processInLinkMsg(HttpServletResponse response,InLinkMsg inLinkMsg) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean processInCustomEvent(HttpServletResponse response,InCustomEvent inCustomEvent) {
		// TODO Auto-generated method stub
		return false;
	}
	/**
	 * 处理关注事件，需认证后的公众号
	 */
	@Override
	protected boolean processInFollowEvent(HttpServletResponse response,InFollowEvent inFollowEvent) {
		// TODO Auto-generated method stub
		OutNewsMsg outMsg=new OutNewsMsg(inFollowEvent);
		outMsg.addNews("敏道公司暑期主题活动报名开始啦",  "大学城的敏道公司暑期招募数学系大牛打造股票交易平台、提供项目实战机会、免费JAVA/微信培训...", "https://mmbiz.qlogo.cn/mmbiz/tpO9S7f6nbFMUd9AvYk418yx4LSjK2QaJfVNQcWWmT3T2wMkg5wrF5G7I7kfBmP0omCYJzA6vszLZnUT0NPgVQ/0?wx_fmt=jpeg", "http://mp.weixin.qq.com/s?__biz=MzAxNzUyNjU5Mw==&amp;mid=304964690&amp;idx=1&amp;sn=65e529fbf0cda9e3b54017e5227bef7c#rd");
		return printText(response,outMsg);
		//return false;
	}
	/**
	 * 处理二维码事件，需认证后的公众号
	 */
	@Override
	protected boolean processInQrCodeEvent(HttpServletResponse response,InQrCodeEvent inQrCodeEvent) {
		// TODO Auto-generated method stub
		Long contractId=null;
		if (InQrCodeEvent.EVENT_INQRCODE_SCAN.equals(inQrCodeEvent.getEvent())){
			contractId=Long.valueOf(inQrCodeEvent.getEventKey());
		}else{//用户已关注，EventKey为qrscene_为前缀，后面为二维码的参数值
			contractId=Long.valueOf(inQrCodeEvent.getEventKey().substring("qrscene_".length()));
		}
		System.out.println("contractId:"+contractId);
		if (contractId!=null){
			//根据合同id得到订单支付的authUrl
			ApiConfig apiConfig = WeixinConfUtils.getApiConfig();
			String REDIRECT_URI=apiConfig.getServerContext()+ "aifang/afwxauth/auth.do";
			String STATE="contractPay_"+contractId;
			
			String url=SnsAccessTokenApi.getAuthorizeURL(apiConfig.getAppId(),  REDIRECT_URI,  true,STATE);
			//租户id
			String openid=inQrCodeEvent.getFromUserName();
			ApiResult result =CustomServiceApi.sendText(openid, "<a href=\""+url+"\">租赁合同支付</a>");
			System.out.println(result);
			//return super.print(response, );
		}
		return  false;
	}

	@Override
	protected boolean processInLocationEvent(HttpServletResponse response,InLocationEvent inLocationEvent) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean processInMassEvent(HttpServletResponse response,InMassEvent inMassEvent) {
		// TODO Auto-generated method stub
		return false;
	}
	/**
	 * 处理菜单消息
	 * @param response
	 * @param inMenuEvent
	 * @return
	 */
	@Override
	protected boolean processInMenuEvent(HttpServletResponse response,InMenuEvent inMenuEvent) {
		// TODO Auto-generated method stub
 
		String eventKey=inMenuEvent.getEventKey();
		String openid=inMenuEvent.getFromUserName();
 
		if (eventKey.startsWith("Md")){
			if ("MdInternetCase".equals(eventKey)){
				OutNewsMsg outMsg=new OutNewsMsg(inMenuEvent);
				outMsg.addNews("互联网+项目案例",  "企业统一建站，软文统一管理，一键预览和发布...",  "http://mmbiz.qpic.cn/mmbiz/9WRAOfic4Lef2mJquSYiaYMbhvbiaibmL321XNJ16cTKaluUwMJnQhdOa0M1JJPnpfwMO9rb3ibia0wktASGdbmx2FdQ/0?wx_fmt=png",  "http://mp.weixin.qq.com/s?__biz=MzIyOTIwNDAwMQ==&mid=100000145&idx=1&sn=934d6d197bdaab572dc275ffbab3c727#rd");
				return printText(response,outMsg);
			}else if ("MdErpCase".equals(eventKey)){
				OutNewsMsg outMsg=new OutNewsMsg(inMenuEvent);
				outMsg.addNews("企业信息化建设案例",  "业务流程办公自动化、可跟踪、可追溯，前台自动适应PC、手机等多终端...",  "http://mmbiz.qpic.cn/mmbiz/9WRAOfic4LefZG5leJjOV16l3tyiaNyLu7MReqexdcRd7gt9HnFrcF1thZeRhg7OMpiaTGcAoGMGzEoGlkU33AqvQ/0?wx_fmt=png",  "http://mp.weixin.qq.com/s?__biz=MzIyOTIwNDAwMQ==&mid=100000149&idx=1&sn=67fde1c1da5d5c674de7da55524319e0#rd");
				return printText(response,outMsg);
			}else if ("MdTrainCase".equals(eventKey)){
				OutNewsMsg outMsg=new OutNewsMsg(inMenuEvent);
				outMsg.addNews("敏道科技和腾讯大粤网达成长期软件技术培训合作计划",  "5月20日，敏道科技和腾讯大粤网合作，为广东省创业团队提供技术管理交流咨询...", "http://mmbiz.qpic.cn/mmbiz/9WRAOfic4LefiaEBMEEOaQkn7A9LSGWBM5P9nSpnAtKibgMiaAjcVbVpbsHAOYZseaBDs5gm9ia1ibA0JfIq7dxXhMNg/0?wx_fmt=jpeg", "http://mp.weixin.qq.com/s?__biz=MzIyOTIwNDAwMQ==&mid=100000130&idx=1&sn=eb4096e01fc1c8e0c12b57a661106666#rd");
				return printText(response,outMsg);
			}
			return true;
		} 
		return false;
 
	}

	/**
	 * 处理语音输入事件
	 */
	@Override
	protected boolean processInSpeechRecognitionResults(HttpServletResponse response,
			InSpeechRecognitionResults inSpeechRecognitionResults) {
			String recongniton = inSpeechRecognitionResults.getRecognition();
			String openid=inSpeechRecognitionResults.getFromUserName();
			String echoTxt="您说："+recongniton;
			 
		     

			return true;
	}

 
	@Override
	protected boolean processInTemplateMsgEvent(HttpServletResponse response,
			InTemplateMsgEvent inTemplateMsgEvent) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean processInShakearoundUserShakeEvent(HttpServletResponse response,
			InShakearoundUserShakeEvent inShakearoundUserShakeEvent) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean processInVerifySuccessEvent(HttpServletResponse response,
			InVerifySuccessEvent inVerifySuccessEvent) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean processInVerifyFailEvent(HttpServletResponse response,InVerifyFailEvent inVerifyFailEvent) {
		// TODO Auto-generated method stub
		return false;
	}
	
	public static void main(String[] args) {
		//System.out.println( "qrscene_4".substring("qrscene_".length()));
		
		String msgContent="报名:李国才，15327817";
		//msgContent =msgContent.replaceAll("，", ",").replaceAll("：", ":");
		if (msgContent.startsWith("报名:") &&  msgContent.indexOf(",")>0){
			String userInfos=msgContent.substring("报名:".length());
			String userInfArr[]=userInfos.split(",");
			System.out.println(userInfArr.length);
		}	
	}
}













